require "sinatra"
require "sinatra/json"
require "sinatra/reloader" if development?
require "mongoid"

Mongoid.load!("./mongoid.yml")
set :protection, :except => [:http_origin]

class Post
  include Mongoid::Document 
  include Mongoid::Timestamps

  field :title, type: String
  field :content, type: String

end

before do
  if ["POST", "PUT"].include? request.request_method
    params.merge!(JSON.parse(request.body.read))
  end
end

get '/' do
  @posts = Post.all
  json :posts => @posts
end

get '/:id' do |id|
  @post = Post.where :id => id
  json :post => @post
end

post '/' do
  json :p => params
end

put '/:id' do |id|
  @post = Post.where(:id => id).first
  p @post.to_json
  @post.update_attributes post_params
  json :post => @post 
end


def post_params
  @post_params = {}
  ["title", "content"].each do |k|
    @post_params[k] = params[k] if params.has_key? k
  end
  @post_params 
end
